package info.cs52.fes.prolog;

import java.io.IOException;
import java.util.Timer;
import java.util.TimerTask;

import alice.tuprolog.Int;
import alice.tuprolog.Library;
import alice.tuprolog.Term;
import alice.tuprolog.Var;

public class FesLibrary extends Library {

	private static final int FORECAST_EXPIRE = 2*60*60;
	private WeatherForecast[] forecasts;
	private WeatherForecastLoader forecastLoader = new WeatherForecastLoader();
	private boolean logEnabled = false;

	public boolean temperature_3(Term day, Var minTemp, Var maxTemp) {
		synchronized (forecastLoader) {
			if (forecasts == null) {
				if (!loadForecasts()) {
					return false;
				}
			}
		}
		
		int dayValue = 0;
		if (day instanceof Var) {
			Var dayVar = (Var) day;
			if (dayVar.isBound() && dayVar.getTerm() instanceof Int) {
				dayValue = ((Int)dayVar.getTerm()).intValue();	
			}
		}
		if (day instanceof Int) {
			dayValue = ((Int)day).intValue();			
		}
		if (dayValue < 0 || dayValue >= forecasts.length) {
			return false;
		}
		WeatherForecast forecast = forecasts[dayValue];
		minTemp.unify(getEngine(), new Int(forecast.getMinTemperature()));
		maxTemp.unify(getEngine(), new Int(forecast.getMaxTemperature()));
		return true;
	}

	public boolean log_1(Term term) {
		if (logEnabled) {
			System.out.println(term.toString());
		}
		return true;
	}

	private boolean loadForecasts() {
		try {
			forecasts = forecastLoader.loadForecasts();
			Timer timer = new Timer();
			timer.schedule(new TimerTask() {
				
				@Override
				public void run() {
					loadForecasts();
				}
			}, FORECAST_EXPIRE);
			return forecasts != null;
		} catch (IOException e) {
			forecasts = null;
			return false;
		}
	}

}
